package com.hc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hc.common.bean.PageBean;
import com.hc.domain.Collect;
import com.hc.domain.Sku;
import com.hc.mapper.CollectMapper;
import com.hc.res.SkuItem;
import com.hc.service.CollectService;
import com.hc.service.SkuService;
import com.hc.trans.SkuTrans;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author hecai
 * @date 2021/12/23 14:40
 */
@Service
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect> implements CollectService {
    @Resource
    private SkuService skuService;

    @Override
    public PageBean<SkuItem> getSkuItemPageBean(Integer pageNum, Integer pageSize, Long userId) {
        //查找到用户收藏的sku的id的集合，按照用户收藏时间的逆序排序
        List<Collect> collectList = baseMapper.selectList(new QueryWrapper<Collect>().eq("user_id", userId).orderByDesc("create_time"));
        List<Integer> skuIdList = collectList.stream().map(item -> item.getSkuId()).collect(Collectors.toList());

        //分页形式查找到用户收藏的所有的sku
        Page<Sku> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Sku> queryWrapper = new QueryWrapper<Sku>()
                .select("id", "name", "specs", "price1", "price2", "img")
                .in("id", skuIdList);
        skuService.page(page, queryWrapper);

        //将最终查询出来的sku按照用户收藏时间的逆序排序
        Map<Integer, Sku> map = page.getRecords().stream().collect(Collectors.toMap(Sku::getId, item -> item, (k1, k2) -> k2));
        page.getRecords().clear();
        for (Integer skuId : skuIdList) {
            page.getRecords().add(map.get(skuId));
        }
        //转换
        PageBean<Sku> skuPageBean = PageBean.init(page);
        PageBean<SkuItem> skuItemPageBean = SkuTrans.MAPPER.skuPage2skuItemPage(skuPageBean);
        return skuItemPageBean;
    }
}
